package com.guass.nettyprotostuff.controller;


import com.alibaba.fastjson.JSON;
import com.guass.nettyprotostuff.pojo.MsgDataInfo;
import com.guass.nettyprotostuff.rpc.client.ClientTest;
import com.guass.nettyprotostuff.rpc.common.ModelMsg;
import com.guass.nettyprotostuff.rpc.common.Session;
import com.guass.nettyprotostuff.rpc.common.SessionManager;
import com.guass.nettyprotostuff.rpc.common.TypeData;
import com.guass.nettyprotostuff.service.RpcService;
import com.guass.nettyprotostuff.zookeeper.DataInfo;
import com.guass.nettyprotostuff.zookeeper.ZookeeperService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Executors;
import java.util.stream.Collectors;

@Slf4j
@RestController
@RequestMapping("/test")
public class TestController {

    @Resource
    private RpcService rpcService;

    @Resource
    private ZookeeperService zookeeperService;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @GetMapping("/client/send/{client_num}/{data_num}/{msg}")
    public ResponseEntity<String> getTestSendData(@PathVariable Integer client_num,
                                                  @PathVariable Integer data_num, @PathVariable String msg) {



        CompletableFuture.runAsync(()->{
            int clientNum = client_num;

            List<Session> sessionList = SessionManager.getInstance().getSessions();
            int num = sessionList.size();
            if (false/*clientNum <= num*/) {
                for (int i = 0; i < clientNum; i++) {
                    Session session = sessionList.get(i);
                    for (int j = 0; j < data_num; j++) {
                        ModelMsg modelMsg = new ModelMsg();
                        modelMsg.setMessageType(TypeData.CUSTOMER);
                        modelMsg.setBody(msg);
                        modelMsg.setMsgId(UUID.randomUUID().toString());

                        session.getChannel().writeAndFlush(modelMsg);
                    }
                }
            }else {
                try {
                    List<String> pathlist = zookeeperService.listAll("/client");
                    if (pathlist != null && pathlist.size() > 0){
                        for (String path : pathlist) {
                            String clientPath = "/client" +"/" +path;
                            String data = zookeeperService.getData(clientPath);
                            DataInfo dataInfo = JSON.parseObject(data, DataInfo.class);
                            if (dataInfo.getCounter() >= clientNum) {
                                MsgDataInfo msgDataInfo = new MsgDataInfo();
                                msgDataInfo.setClientCount(clientNum);
                                msgDataInfo.setDataCount(data_num);
                                msgDataInfo.setClientPath(clientPath);
                                msgDataInfo.setMsg(msg);

                                stringRedisTemplate.convertAndSend("guassTopic",JSON.toJSONString(msgDataInfo));
                                break;
                            }else {
                                MsgDataInfo msgDataInfo = new MsgDataInfo();
                                msgDataInfo.setClientCount(dataInfo.getCounter());
                                msgDataInfo.setDataCount(data_num);
                                msgDataInfo.setClientPath(clientPath);
                                msgDataInfo.setMsg(msg);

                                stringRedisTemplate.convertAndSend("guassTopic",JSON.toJSONString(msgDataInfo));

                                clientNum -= dataInfo.getCounter();
                            }
                        }
                    }

                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }, Executors.newCachedThreadPool());

        return ResponseEntity.ok(client_num * data_num + " 条测试数据发送成功  ==>  "  + new Date());
    }


    @GetMapping("/client/count")
    public ResponseEntity<String> getTestClientCount() {

        int countTotal = 0;
        try{
            List<String> pathlist = zookeeperService.listAll("/node");

            if (pathlist != null && pathlist.size() > 0) {


                for (String path : pathlist) {
                    String data = zookeeperService.getData("/node" +"/" +path);

                    DataInfo dataInfo = JSON.parseObject(data, DataInfo.class);
                    countTotal += dataInfo.getCounter();
                }
            }

        }catch (Exception e){

        }

        return ResponseEntity.ok("服务器 客户端总数 ==>  " + countTotal);
    }


    @GetMapping("/count")
    public ResponseEntity<String> getCount() {
        return ResponseEntity.ok("total count ==>  " + rpcService.getChannelCount());
    }

    @GetMapping("/send/{msg}")
    public ResponseEntity<String> sendAll(@PathVariable String msg){
        rpcService.sendMessageToAll(msg);
        return ResponseEntity.ok("send ok");
    }

    @GetMapping("/zk/{counter}")
    public ResponseEntity<String> testZk(@PathVariable("counter") int counter){



//        zookeeperService.updateCounter(counter);
        String s = null;
        try {

            List<String> strings = zookeeperService.listAll("/node");
            log.info("guass sts {}",strings);
            byte[] bytes = zookeeperService.getCuratorFramework().getData().forPath(zookeeperService.getForPath());

            s = new String(bytes);


        } catch (Exception e) {
            e.printStackTrace();
        }

        return ResponseEntity.ok(s);
    }
}
